<template>
    <!-- 操作按钮区 -->
   <div class="action-buttons">
     <el-button type="primary" @click="batchSaveDetails">添加</el-button>
     <el-button type="primary" @click="Export">导出</el-button>
     
   </div>
   
   <div>
       <!-- 查询条件部分 -->
      <div class="search-section">
           <el-form :inline="true" :model="prolist">
               <el-form-item label="检验主题">
                   <el-input v-model="prolist.InspectionSubject" placeholder="输入检验主题"></el-input>
               </el-form-item>
               <el-form-item label="检验单号">
                   <el-input v-model="prolist.InspectionOrderNumber" placeholder="输入检验单号"></el-input>
               </el-form-item>
               <el-form-item label="检验日期">
                   <el-date-picker v-model="prolist.InspectionDate" type="date" placeholder="选择日期"></el-date-picker>
               </el-form-item>
               <el-form-item label="采购单号">
                   <el-input v-model="prolist.PurchaseOrderNumber" placeholder="输入采购单号"></el-input>
               </el-form-item>
               <el-form-item label="采购日期">
                   <el-date-picker v-model="prolist.PurchaseDate" type="date" placeholder="选择日期"></el-date-picker>
               </el-form-item>
               <el-form-item label="供应商名称">
                   <el-input v-model="prolist.SupplierName" placeholder="输入供应商名称"></el-input>
               </el-form-item>
               <el-form-item>
                   <el-button @click="ShowMaterials">查询</el-button>
               </el-form-item>
           </el-form>
       </div>

       <div class="page-title">
       <h2>到货质检列表</h2>
       </div>
       <!-- 生产计划列表 -->
       <div class="table-container">
            <el-table :data="planList" style="width: 100%">
               <el-table-column type="selection" width="55"></el-table-column>
               <el-table-column type="index" label="序号" width="50"></el-table-column>
               <el-table-column prop="inspectionSubject" label="检验主题"></el-table-column>
               <el-table-column prop="inspectionOrderNumber" label="检验单号"></el-table-column>
               <el-table-column prop="inspectionDate" label="检验日期">
                    <template #default="scope">
                   {{ formatDate(scope.row.inspectionDate) }}
                   </template>
               </el-table-column>
               <el-table-column prop="inspectionPersonnel" label="检验人员"></el-table-column>
               <el-table-column prop="department" label="所在部门"></el-table-column>
               <el-table-column prop="contactInformation" label="联系方式"></el-table-column>
               <el-table-column prop="purchaseOrderNumber" label="采购单号"></el-table-column>
               <el-table-column prop="purchaseDate" label="采购日期">
                    <template #default="scope">
                   {{ formatDate(scope.row.purchaseDate) }}
                   </template>
               </el-table-column>
               <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
               <el-table-column prop="contactPerson" label="联系人"></el-table-column>
               <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
               <el-table-column prop="purchasingPersonnel" label="采购人员"></el-table-column>
               <el-table-column prop="purchasingDepartment" label="采购部门"></el-table-column>
               <el-table-column prop="contactMethod" label="联系方式"></el-table-column>
               <el-table-column prop="relatedProject" label="关联项目"></el-table-column>
               <el-table-column prop="remarks" label="备注"></el-table-column>
                  <el-table-column prop="right" label="操作">
                   <template #default="scope">
                       <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.basicInfoid)">详情页</el-button>
                       <el-button  type="text" @click="DeleteProductionPlanning(scope.row.basicInfoid)">删除</el-button>
                   </template>
               </el-table-column>
           </el-table>
       </div>
        <div style="margin-top: 20px">
           <el-pagination
               v-model:current-page="page.pageindex"
               v-model:page-size="page.pageSize"
               :page-sizes="[5, 20, 25, 30]"
               :background="true"
               prev-text="上一页"
               next-text="下一页"
               layout="total, sizes, prev, pager, next, jumper"
               :total="total.totalCount"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
           />
       </div>
   </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus';
import router from '@/router';
import axios from 'axios';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
// 定义搜索表单数据
const prolist = ref({
    InspectionSubject:'',
    InspectionOrderNumber:'',
    InspectionDate:'',
    PurchaseOrderNumber:'',
    PurchaseDate:'',
    SupplierName:'',
});

// 定义分页总数
const total = ref({
 totalCount: 0,
 pageCount:0,
});
// 定义分页对象
const page = ref({
   pageindex: 1,
   pageSize: 5,
});

// 表格数据
const planList = ref([
   {
    "basicInfoid": 0,
      "inspectionSubject": "",
      "inspectionOrderNumber": "",
      "inspectionDate": "",
      "inspectionPersonnel": "",
      "department": "",
      "contactInformation": "",
      "purchaseOrderNumber": "",
      "purchaseDate": "",
      "supplierName": "",
      "contactPerson": "",
      "contactPhone": "",
      "purchasingPersonnel": "",
      "purchasingDepartment": "",
      "contactMethod": "",
      "relatedProject": "",
      "remarks": "",
      "isDel": false
   } 
]);

// 日期格式化
const formatDate = (dateStr) => {
 if (!dateStr) return '';
 const date = new Date(dateStr);
 const year = date.getFullYear();
 const month = String(date.getMonth() + 1).padStart(2, '0');
 const day = String(date.getDate()).padStart(2, '0');
 const hour = String(date.getHours()).padStart(2, '0');
 const minute = String(date.getMinutes()).padStart(2, '0');
 const second = String(date.getSeconds()).padStart(2, '0');
 return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 表格引用
const tableRef = ref(null);
// 全选状态
const allChecked = ref(false);
// 上传文件引用
const uploadRef = ref(null);
// 存储选择的文件
const selectedFile = ref(null);
// 上传加载状态
const uploadLoading = ref(false);

// 显示物料列表
const ShowMaterials = () => {
   Materialread.get("f-read/api/Arrival/GetBasicInfo", {
       params: {
           pageindex: page.value.pageindex,
           pageSize: page.value.pageSize,
           InspectionSubject: prolist.value.InspectionSubject,
           InspectionOrderNumber: prolist.value.InspectionOrderNumber,
           InspectionDate: prolist.value.InspectionDate,
           PurchaseOrderNumber: prolist.value.PurchaseOrderNumber,
           PurchaseDate: prolist.value.PurchaseDate,
           SupplierName: prolist.value.SupplierName,
       }
   }).then((res) => {
       planList.value = res.data.data.list;
       total.value.totalCount = res.data.data.totalCount;
       total.value.pageCount = res.data.data.pageCount;
       allChecked.value = false;
   }).catch((error) => {
       console.error('接口请求失败:', error);
       ElMessage.error('数据获取失败，请稍后重试');
   });
};

// 编辑跳转修改
const GetBYIdProductionPlanning = (basicInfoid) => {
   router.push({
       name: 'UpdateArrival',
       query: { basicInfoid }
   });
};

// 跳转添加
const batchSaveDetails = () => {
    router.push({ name: 'AddFeeding' });
};

// 导出
const Export = async () => {
  try {
    const res = await Materialread.get("f-read/api/Arrival/ExportToExcel", {
      responseType: 'blob'
    });
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '到货质检信息表.xlsx');
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出数据出错:', error);
    if (axios.isAxiosError(error) && error.response) {
      ElMessage.error(`导出失败，状态码: ${error.response.status}`);
    } else {
      ElMessage.error('导出失败，请检查网络或联系管理员');
    }
  }
};

// 处理文件变化
const handleFileChange = (file, fileList) => {
  selectedFile.value = file.raw;
  console.log('选择的文件:', selectedFile.value);
};

// 处理上传成功
const handleUploadSuccess = (response) => {
  if (response && response.code === 200) {
    ElMessage.success('导入成功');
    ShowMaterials();
    uploadRef.value.clearFiles();
    selectedFile.value = null;
  } else {
    ElMessage.error(`导入失败：${response.message || '未知错误'}`);
  }
  uploadLoading.value = false;
};

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传错误:', error);
  ElMessage.error('导入失败，请检查网络或文件格式');
  uploadLoading.value = false;
};

// 执行上传
const importData = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }

  uploadLoading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const response = await Materialread.post(
      'f-read/api/Arrival/ImportExcel', 
      formData,
      {
        headers: { 
          'Content-Type': 'multipart/form-data'
        }
      }
    );
    
    handleUploadSuccess(response.data);  
  } catch (error) {
    console.error('导入错误:', error);
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`导入失败，状态码: ${error.response.status}`);
      } else {
        ElMessage.error('导入失败，请检查网络连接');
      }
    } else {
      ElMessage.error('导入失败，请检查文件格式或联系管理员');
    }
    uploadLoading.value = false;
  }
};

// 删除单条记录
const DeleteProductionPlanning = async (basicInfoid) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确认删除该条记录？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    if (confirmResult === 'confirm') {
      const response = await Materialwrite.post(
        `f-write/api/Arrival/DelBasicInfo`,
        { basicInfoid: basicInfoid.toString() },
        {
          params: { BasicInfoid: basicInfoid.toString() }
        }
      );
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        ShowMaterials();
      } else {
        ElMessage.error(`删除失败：${response.data.message}`);
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除错误:', error);
      ElMessage.error('删除失败，请检查网络或联系管理员');
    }
  }
};

// 选中的 ID 列表
const checkedIds = ref([]);

// 处理全选
const handleCheckAllChange = (value) => {
  if (value) {
    checkedIds.value = planList.value.map(item => item.feedingId);
  } else {
    checkedIds.value = [];
  }
  allChecked.value = value;
};

// 分页事件处理
const handleSizeChange = (val) => {
  page.value.pageSize = val;
  ShowMaterials();
};

const handleCurrentChange = (val) => {
  page.value.pageindex = val;
  ShowMaterials();
};

// 页面加载时初始化
onMounted(() => {
  ShowMaterials();
})
</script>

<style scoped>
.search-section {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  max-height: 500px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.upload-demo {
  display: inline-block;
}

.page-title {
  margin-bottom: 15px;
}

/* 表格样式优化 */
.el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-table .cell {
  padding: 8px 0;
}

/* 分页样式优化 */
.el-pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>